package com.hucc.redislock.command;

import com.hucc.redislock.RedisLockContext;
import com.hucc.redislock.result.CommandResult;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

public class AddLockRedisCommand<Long> extends AbstractRedisCommand<Long> {

    public AddLockRedisCommand(String lockName, String threadName) {
        super(lockName, threadName);
    }

    @Override
    public CommandResult<Long> execute() {
        String script =
                "if (redis.call('exists', KEYS[1]) == 0) then " +
                    "redis.call('hset', KEYS[1], ARGV[2], 1); " +
                    "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                    "return nil; " +
                "end; " +
                "if (redis.call('hexists', KEYS[1], ARGV[2]) == 1) then " +
                    "redis.call('hincrby', KEYS[1], ARGV[2], 1); " +
                    "redis.call('pexpire', KEYS[1], ARGV[1]); " +
                    "return nil; " +
                "end; " +
                "return redis.call('pttl', KEYS[1]);";
        List<String> keys = new ArrayList<String>();
        keys.add(lockName);

        List<String> args = new ArrayList<String>();
        args.add(String.valueOf(RedisLockContext.getRedisLockConfig().getLockWatchdogTimeout()));
        args.add(threadName);

        Long eval = (Long) executeScript(script, keys, args);

        CommandResult result = new CommandResult();
        result.setSuccess(eval == null);
        result.setData(eval);
        return result;
    }
}
